import React, { useContext, useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Table, InputNumber, Button, Form, Tabs, Card, message, Space, Modal } from 'antd';
import { FormInstance } from 'antd/lib/form';

import { EmpSelect } from '@/components/FormItemSelect';
import MfgMtlSearch from './MfgMtlSearch';
import request from '@/utils/request';
import MyDataTable from '@/components/MyDataTable';
import PrintModal from '@/components/PrintModal';
import TempleteIssue from '../PrintTemplete/TempleteIssue';

const apiURL = '/api/services/app/JobMtl/';
const EditableContext = React.createContext<FormInstance<any> | null>(null);
const { TabPane } = Tabs;
//形参类型
interface Item {
  key: string;
  jobComplete: boolean;
  issuedComplete: boolean;
  jobNum: string;
  pickNum: string;
  assemblySeq: number;
  mtlSeq: number;
  partNum: string;
  partDescription: string;
  qtyPer: number;
  requiredQty: number;
  fixedQty: boolean;
  ium: string;
  relatedOperation: number;
  relatedOpRev: string;
  issuedQty: number;
  unIssuedQty: number;
  reqDate: string;
  warehouseCode: string;
  binNum: string;
  id: string;
  pickQty: number;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<any>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      if (values.pickQty > record.unIssuedQty) {
        message.warning('领料数将超出需求量');
        return;
      }
      record.pickQty = values.pickQty;
      handleSave(record);
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `请输入${title} .`,
          },
        ]}
      >
        <InputNumber ref={inputRef} onPressEnter={save} onBlur={save} min={0} step="0.01" max={record.unIssuedQty} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];
interface DataType {
  key: React.Key;
  jobComplete: boolean;
  issuedComplete: boolean;
  jobNum: string;
  assemblySeq: number;
  mtlSeq: number;
  partNum: string;
  partDescription: string;
  qtyPer: number;
  requiredQty: number;
  fixedQty: boolean;
  ium: string;
  relatedOperation: number;
  relatedOpRev: string;
  issuedQty: number;
  unIssuedQty: number;
  reqDate: string;
  warehouseCode: string;
  binNum: string;
  id: string;
  pickQty: number;
  pickUser: string;
  pickedQty: number;
  allowPickQty: number
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
class EditableTable extends React.Component<any, any> {
  columnLing: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[];
  constructor(props: EditableTableProps) {
    super(props);
    this.columnLing = [
      {
        title: '工单号',
        dataIndex: 'jobNum',
        align: 'center',
        width: 80,
      },
      {
        title: '半成品号',
        dataIndex: 'assemblySeq',
        align: 'center',
        width: 100,
      },
      {
        title: '物料号',
        dataIndex: 'mtlSeq',
        align: 'center',
        width: 100,
      },
      {
        title: '物料编码',
        dataIndex: 'partNum',
        align: 'center',
        width: 120,
      },
      {
        title: '描述',
        dataIndex: 'partDescription',
        ellipsis: true,
        width: 200,
      },
      {
        title: '需求量',
        dataIndex: 'requiredQty',
        align: 'center',
        width: 100,
      },
      {
        title: '发料量',
        dataIndex: 'issuedQty',
        align: 'center',
        width: 100,
      },
      {
        title: '可领量',
        dataIndex: 'allowPickQty',
        align: 'center',
        width: 100,
        render: (text: any, record: any) => <span>{record.allowPickQty}</span>
      },
      {
        title: '单位',
        dataIndex: 'ium',
        align: 'center',
        width: 100,
      },
      {
        title: '本次领量',
        dataIndex: 'pickQty',
        editable: true,
        width: 120,
        fixed: 'right'
      }
    ];
    this.state = {
      selectedKeys: [],
      selectedRows: [],
      visible: false,
      dataSource: [],
      params: { skipCount: 0, jobComp: 0, jobRelease: 1 },
      pageIndex: 1,
      pageSize: 10,
      loading: false,
      selectedEmp: '',
      printData: [],
      freshNum: 0,
    };
  }

  printArea: any = React.createRef();
  componentDidMount() {
    this.query();
  }
  query = () => {
    //接口
    const { params, pageIndex, pageSize } = this.state;
    var datas = params;
    datas.skipCount = (pageIndex - 1) * pageSize;
    datas.maxResultCount = pageSize;
    this.setState({ loading: true });
    request(apiURL + 'GetAllowPickMtl', {
      method: 'GET',
      params: datas,
    }).then((response) => {
      let resp = response.result;
      if (resp) {
        resp.items.forEach((item: any) => {
          item.pickQty = item.allowPickQty;
        });
        this.setState({ dataSource: resp.items, totalCount: resp.totalCount, loading: false });
      }
    });
  };
  /**
   * @param values 搜索领料信息
   */
  handleSearch = (params: any) => {
    const { actTab, freshNum } = this.state;
    if (actTab === '1') {
      params.jobComp = 0;
      this.setState({ params },
        this.query,
      );
    }
    else {
      this.setState({ params, freshNum: freshNum + 1 });
    }
  };
  /**
   * 控制更新模态框显示
   * @param {boolean} visible 是否显示
   */
  switchVisible = (visible = false) => {
    const { selectedRows } = this.state;
    if (selectedRows.length <= 0) {
      message.error('请选择所需物料');
    } else {
      this.setState({
        visible,
      });
    }
  };
  /**
   * @param selectedKeys 选择单元格
   */
  handleRowSelect = (selectedKeys: any, selectedRows: any) => {
    selectedRows.forEach((item: DataType) => {
      if (item.pickQty == 0) {
        message.warning('请填写本次领量');
      }

    });
    this.setState({
      selectedKeys,
      selectedRows,
    });
  };
  //修改确认编辑框
  handleSave = (row: DataType) => {
    let newData: DataType[] = [];
    const { dataSource } = this.state
    dataSource.forEach((element: DataType) => {
      if (element.id === row.id) {
        element.pickQty = row.pickQty;
      }
      newData.push(element);
    });
    this.setState({ dataSource: newData });
  };
  /**
   * 确认领料
   */
  handleSubmit = async () => {
    const { selectedRows, selectedEmp } = this.state;
    if (selectedRows.length <= 0) {
      return message.warning('请选择领料工单');
    }
    if (!selectedEmp) {
      return message.warning('请选择领料人');
    }

    var isok: boolean = true;
    selectedRows.forEach((item: DataType) => {
      item.pickUser = selectedEmp;
      if (item.pickQty > item.allowPickQty) {
        message.warning('领料数不得超出需求量');
        isok = false;
      }
    });

    if (isok) {
      var resp = await request(apiURL + 'AppIssueMtl', {
        method: 'POST',
        data: selectedRows,
      })
      if (resp && resp.success) {
        message.success('领料成功！')
        this.query();
      }
      this.setState({ printData: selectedRows });
      this.switchVisible();
    }
  };
  selectEmp = (values: any) => {
    this.setState({ selectedEmp: values });
  };
  setRowSelection = (items: any) => {
    this.setState({ printData: items });
  }
  doPrint = () => {
    this.setState({ visible2: true })
  };
  quickFill = () => {
    const { dataSource } = this.state;
    dataSource.forEach((item: any) => {
      item.pickQty = item.allowPickQty;
    });
    this.setState({ dataSource })
  }
  delAppMtl = () => {
    const { printData, freshNum } = this.state;
    var ids: any = [];
    printData.forEach((item: any) => {
      ids.push(item.id);
    });
    request(apiURL + 'DelAppMtl', {
      method: 'POST',
      data: ids,
    }).then((response) => {
      this.setState({ freshNum: freshNum + 1 });
    });
  }
  render() {
    const { selectedKeys, dataSource, params, pageSize, totalCount } = this.state;
    const rowSelection = {
      selectedRowKeys: selectedKeys,
      onChange: this.handleRowSelect,
    };
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columnLing.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record: DataType) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const column2 = [
      {
        title: '领料单号',
        dataIndex: 'pickNum',
        width: 130,
      },
      {
        title: '工单号',
        dataIndex: 'jobNum',
        width: 80,
      },
      {
        title: '半成品号',
        dataIndex: 'assemblySeq',
        align: 'center',
        width: 80,
      },
      {
        title: '物料号',
        dataIndex: 'mtlSeq',
        align: 'center',
        width: 100,
      },
      {
        title: '物料编码',
        dataIndex: 'partNum',
        align: 'center',
        width: 120,
      },
      {
        title: '描述',
        dataIndex: 'partDescription',
        ellipsis: true,
        width: 200,
      },
      {
        title: '需求量',
        dataIndex: 'requiredQty',
        align: 'center',
        width: 100,
      },
      {
        title: '领料人',
        dataIndex: 'pickUser',
        width: 70,
      },
      {
        title: '领料量',
        dataIndex: 'pickQty',
        editable: true,
        width: 80,
        fixed: 'right'
      }
    ];
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <MfgMtlSearch onSearch={this.handleSearch} hideSearchItem={false}>
            <EmpSelect
              width={100}
              name="empId"
              label="领料人"
              onChange={this.selectEmp}
            />
          </MfgMtlSearch>
          <Tabs defaultActiveKey="1" onChange={(e) => this.setState({ actTab: e })}>
            <TabPane tab={<span>领料</span>} key="1">
              <Space style={{ marginBottom: 8, float: 'right' }}>
                <Button type="primary" onClick={this.handleSubmit}>
                  申请领料
                </Button>
                <Button type="primary" onClick={this.quickFill}>
                  一键填充
                </Button>
              </Space>
              <Table
                rowKey="id"
                components={components}
                rowClassName={() => 'editable-row'}
                dataSource={dataSource}
                columns={columns as ColumnTypes}
                rowSelection={rowSelection}
                scroll={{ x: '1800' }}
                loading={this.state.loading}

                pagination={{
                  onChange: page => {
                    this.setState({ pageIndex: page }, () => {
                      this.query();
                    });
                  },
                  pageSize,
                  total: totalCount,
                  showTotal: total => `共 ${total} 条`
                }}
              />

            </TabPane>
            <TabPane tab={<span>领料记录</span>} key="2">
              <Space style={{ marginBottom: 8, float: 'right' }}>
                <Button type="primary" onClick={this.doPrint}>
                  打印
                </Button>
                <Button danger onClick={this.delAppMtl}>
                  撤销
                </Button>
              </Space>
              <MyDataTable
                act="GetIssueMtl"
                columns={column2}
                freshNum={this.state.freshNum}
                pageSize={this.state.pageSize}
                control="JobMtl"
                rowSelection={(items: any) => this.setRowSelection(items)}
                params={params}
                bordered={false}>
              </MyDataTable>
            </TabPane>
          </Tabs>
        </Card>
        <div ref={(ref) => (this.printArea = ref)} hidden>
          <TempleteIssue data={this.state.printData} ref={(ref: any) => (this.printArea = ref)} hidden />
        </div>
        <Modal
          width={1024}
          title="领料单打印"
          visible={this.state.visible2}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible2: false })}
          footer={false}
        >
          <PrintModal>
            <TempleteIssue data={this.state.printData} configData={this.props.currentConfig} />
          </PrintModal>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp,user }: API.IConnectState) => ({
  response: Abp.response,
  currentConfig: user.currentConfig,
}))(EditableTable);
